﻿Imports System.Data.SqlClient
Public Class FormProduct

    Public Sub LoadData()
        Cmd.Parameters("@s") = "%" & txtSearch.Text & "%"
        Me.dgv.DataSource = Cmd.ExecuteDataTable("select ProductId,ProductCode,ProductName,C.CategoryId,C.CategoryName,T.TypeId,T.TypeName,Price,MinimumPrice from Product P inner join Category C on P.CategoryId = C.CategoryId inner join Type T on C.TypeId = T.TypeId where upper (ProductName+T.TypeName+C.CategoryName) like upper(@s) and P.Active = 1 order by T.TypeName")
    End Sub
    Private Sub FormProduct_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadData()
        UI.FormatDataGrid(Me.dgv)
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim frm As New FormProductEditor
        frm.ShowDialog()
    End Sub

    Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
        LoadData()
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Me.dgv.SelectedRows.Count = 0 Then
            Exit Sub
        End If

        If MessageBox.Show("Are you want to delete this item", "Delet", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            Exit Sub
        End If

        Dim row = dgv.SelectedRows(0)
        Dim id = row.Cells(0).Value

        Cmd.Parameters("@Id") = id
        Cmd.ExecuteNonQuery("UPDATE Product SET Active=0 WHERE ProductId=@Id")

        LoadData()

    End Sub

    Public Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        If Me.dgv.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Dim row = dgv.SelectedRows(0)

        Dim frm As New FormProductEditor()
        frm.PID.Text = row.Cells("ProductId").Value
        frm.txtProductCode.Text = row.Cells("ProductCode").Value
        frm.txtProductName.Text = row.Cells("productName").Value
        frm.cboCategory.Text = row.Cells("CategoryName").Value
        frm.cboType.Text = row.Cells("TypeName").Value
        frm.txtPrice.Text = row.Cells("Price").Value
        frm.txtMinimumPrice.Text = row.Cells("MinimumPrice").Value
        If (frm.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            LoadData()
        End If
    End Sub
End Class